package com.shell.governor.user.rx;

import com.shell.bee.base.utils.StringUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.governor.authorization.po.PubRole;
import com.shell.governor.authorization.service.PubRoleService;
import com.shell.governor.authorization.service.PubUserRoleService;
import com.shell.governor.user.UserEvent;
import com.shell.governor.user.po.PubUser;
import com.shell.governor.user.po.PubUserRole;
import com.shell.governor.user.vo.PubUserVo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SetUserRoleSubscriber extends OnErrorNotImplementedSubscriber<UserEvent> {
	@Autowired
	PubUserRoleService userRoleService;
	@Autowired
	PubRoleService roleService;

	public void onApplicationEvent(UserEvent event) {
		PubUser user = event.getUser();
		PubUserVo userVo = event.getUserVo();

		PubUserRole userRole = new PubUserRole();
		userRole.setUserId(user.getUserId());
		userRole.setOrganId(CommonDataUtil.getCurEntId());
		List<PubUserRole> userRoles = this.userRoleService.selectByEntity(userRole);
		for (PubUserRole ur : userRoles) {
			this.userRoleService.delete(ur);
		}
		String roleCodes = userVo.getRoleCodes();
		if (StringUtil.notEmpty(roleCodes)) {
			String[] roleCodesArr = roleCodes.split(",");
			List<PubRole> roles = this.roleService.selectRolesByCodes(roleCodesArr);
			for (PubRole role : roles) {
				PubUserRole ur = new PubUserRole();
				ur.setOrganId(CommonDataUtil.getCurEntId());
				ur.setRoleId(role.getRoleId());
				ur.setUserId(user.getUserId());
				this.userRoleService.save(ur);
			}
		}
	}
}
